package tools;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * Créer une emprinte pour un mot de passé.
 * @author Guillaume Poças & Jean-François Augé
 */
public class PasswordSecurity {
	
	/**
	 * Créer une emprinte de la forme :
	 * HMAC (K,m) = H ((K ⊕ opad) ∥ H ((K ⊕ ipad) ∥ m))
	 * @param pass
	 * @param seed
	 * @return l'emprinte
	 */
	public final static String sha256_2(String pass, String seed) {
		MessageDigest md;
		String dg = "";
		String Kopad = "";
		String Kipad = "";
		StringBuilder sb = new StringBuilder();

		char iPad = 0x36;
		char oPad = 0x5c;
		
		for(int i = 0; i < pass.length(); i++)
		    sb.append((char)(pass.charAt(i) ^ iPad));
		Kipad = sb.toString();
		
		for(int i = 0; i < pass.length(); i++)
		    sb.append((char)(pass.charAt(i) ^ oPad));
		Kopad = sb.toString();
		
		try {
			md = MessageDigest.getInstance("SHA-256");
			dg = new String( md.digest((Kopad + new String(md.digest((Kipad+seed).getBytes())) ).getBytes()) );
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return dg;
	}
	
	/**
	 * Créer une emprinte simple.
	 * @param pass
	 * @param seed
	 * @return l'emprinte
	 */
	public final static byte[] sha256(String pass, String seed) {
		MessageDigest md;
		byte[] dg = null;
		try {
			md = MessageDigest.getInstance("SHA-256");
			dg = md.digest((pass + seed).getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return dg;
	}
	
	
	// tests
	public static void main(String[] args) {
		// random seed
		Random rng = new Random();
		rng.setSeed(System.currentTimeMillis());
		byte[] tab = new byte[32];
		
		String seed = "";
		for(int i=0; i<10; i++) {
			rng.nextBytes(tab);
			seed = new String(tab);
			System.out.println("graine "+seed);
			System.out.println("emprinte "+sha256_2("kraken_pwd", seed));
		}
		
	}

}
